package com.itheima.servcie;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.bean.CodeBean;
import com.itheima.dbservice.AnnouncementsServiceApi;
import com.itheima.dbservice.UserInfoServiceApi;
import com.itheima.dbservice.UserService;
import com.itheima.exception.CommonException;
import com.itheima.mongoservice.CommentsServiceApi;
import com.itheima.mongoservice.FriendServiceApi;
import com.itheima.mongoservice.UserLikeServiceApi;
import com.itheima.pojo.Announcement;
import com.itheima.pojo.User;
import com.itheima.pojo.UserInfo;
import com.itheima.pojo.mongo.Comment;
import com.itheima.pojo.mongo.Friend;
import com.itheima.pojo.mongo.UserLike;
import com.itheima.template.HuanXinTemplate;
import com.itheima.vo.AnnouncementsVo;
import com.itheima.vo.FriendInfoVo;
import com.itheima.vo.UserInfoVo;
import com.itheima.vo.mongo.AllVo;
import com.itheima.vo.mongo.UserInfoLikeVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MessagesService {
    @DubboReference
    private FriendServiceApi friendServiceApi;
    @DubboReference
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private AnnouncementsServiceApi announcementsServiceApi;
    @DubboReference
    private UserLikeServiceApi userLikeServiceApi;
    @DubboReference
    private CommentsServiceApi commentsServiceApi;

    public void addFriend(Integer userId) {
        String uid = stringRedisTemplate.opsForValue().get(CodeBean.ID);
        //获取对应的个人信息
        User userInfo = userService.getUser(uid);
        User friendInfo = userService.getUser(Convert.toStr(userId));
        if (ObjectUtil.equal(userInfo.getHxUser(), friendInfo.getHxUser())){
            throw new CommonException("您不能添加自己为好友");
        }
        //添加环信好友
        Boolean aBoolean = huanXinTemplate.addContact(userInfo.getHxUser(), friendInfo.getHxUser());
        if (!aBoolean){
            throw new CommonException("添加好友失败，日志已上报");
        }
        //判断好友关系是否存在
        boolean res1 = friendServiceApi.isFriendExist(userInfo.getId(), Convert.toLong(userId));
        if (!res1){
            //封装
            Friend friend = new Friend();
            friend.setUserId(userInfo.getId());
            friend.setFriendId(Convert.toLong(userId));
            friend.setCreated(System.currentTimeMillis());
            //添加到friend集合中
            friendServiceApi.addFriends(friend);
        }
        boolean res2 = friendServiceApi.isFriendExist(Convert.toLong(userId), userInfo.getId());
        if (!res2){
            //封装
            Friend friend = new Friend();
            friend.setUserId(Convert.toLong(userId));
            friend.setFriendId(userInfo.getId());
            friend.setCreated(System.currentTimeMillis());
            //添加到friend集合中
            friendServiceApi.addFriends(friend);
        }
    }

    public AllVo getFriendsList(Integer page, Integer pagesize, String keyword) {
        //获取当前登录者id
        Long id = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
        List<Friend> friendList = friendServiceApi.getFriends(page, pagesize, id);
        List<FriendInfoVo> item = new ArrayList<>();
        //模糊查询
        if (ObjectUtil.isNull(keyword)) {
            for (Friend friend : friendList) {
                //查询朋友信息并封装
                UserInfo friendInfo = userInfoServiceApi.getUserInfoById(friend.getFriendId());
                FriendInfoVo friendInfoVo = new FriendInfoVo();
                friendInfoVo.setId(Convert.toInt(friendInfo.getId()));
                friendInfoVo.setUserId(CodeBean.HX_USER_PREFIX + friendInfo.getId());
                friendInfoVo.setAvatar(friendInfo.getAvatar());
                friendInfoVo.setNickname(friendInfo.getNickname());
                friendInfoVo.setGender(friendInfo.getGender());
                friendInfoVo.setAge(friendInfo.getAge());
                friendInfoVo.setCity(friendInfo.getCity());
                //添加到集合
                item.add(friendInfoVo);
            }
        }else {
            for (Friend friend : friendList) {
                //查询朋友信息并封装
                UserInfo friendInfo = userInfoServiceApi.getUserInfoByIdAndKeyword(friend.getFriendId(), keyword);
                if (ObjectUtil.isNull(friendInfo)){
                    continue;
                }
                FriendInfoVo friendInfoVo = new FriendInfoVo();
                friendInfoVo.setId(Convert.toInt(friendInfo.getId()));
                friendInfoVo.setUserId(CodeBean.HX_USER_PREFIX + friendInfo.getId());
                friendInfoVo.setAvatar(friendInfo.getAvatar());
                friendInfoVo.setNickname(friendInfo.getNickname());
                friendInfoVo.setGender(friendInfo.getGender());
                friendInfoVo.setAge(friendInfo.getAge());
                friendInfoVo.setCity(friendInfo.getCity());
                //添加到集合
                item.add(friendInfoVo);
            }
        }
        //封装到AllVo并返回
        AllVo allVo = new AllVo();
        allVo.setItems(item.toArray());
        allVo.setPagesize(pagesize);
        allVo.setPage(page);
        allVo.setCounts(friendList.size());
        allVo.setPages(friendList.size()/ pagesize +1);
        return allVo;
    }

    public UserInfoVo getHuanxinUser(String huanxinId) {
        User user = userService.getByHuanxinId(huanxinId);
        //查询userInfo
        UserInfo userInfo = userInfoServiceApi.getUserInfoById(user.getId());
        //封装并返回
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        if (userInfo.getAge() != null){
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    public AllVo announcements(Integer page, Integer pagesize) {
        //查询公告信息
        List<Announcement> announcements = announcementsServiceApi.getAnnouncements(page, pagesize);
        List<AnnouncementsVo> list = new ArrayList<>();
        for (Announcement announcement : announcements) {
            AnnouncementsVo announcementsVo = new AnnouncementsVo();
            announcementsVo.setId(Convert.toStr(announcement.getId()));
            announcementsVo.setDescription(announcement.getDescription());
            announcementsVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(announcement.getCreated()));
            announcementsVo.setTitle(announcement.getTitle());
            list.add(announcementsVo);
        }
        //封装并返回
        AllVo allVo = new AllVo();
        allVo.setPage(page);
        allVo.setPagesize(pagesize);
        allVo.setCounts(announcements.size());
        allVo.setPages(Convert.toInt(announcements.size())/pagesize + 1);
        allVo.setItems(list.toArray());
        return allVo;
    }

    public AllVo loves(Integer page, Integer pagesize) {
        //获取当前用户id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
        //获取喜欢的用户id
        List<UserLike> userLike = userLikeServiceApi.getLikeUserInfos(uid);
        if (ObjectUtil.isNull(userLike) || userLike.size() == 0){
            throw new CommonException("暂无信息");
        }
        //查询对应信息
        List<UserInfoLikeVo> list = new ArrayList<>();
        for (UserLike like : userLike) {
            UserInfo userInfo = userInfoServiceApi.getUserInfoById(like.getUserId());
            UserInfoLikeVo userInfoLikeVo = getUserInfoLikeVo(userInfo);
            userInfoLikeVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(like.getCreated()));
            list.add(userInfoLikeVo);
        }
        AllVo allVo = new AllVo();
        allVo.setPage(page);
        allVo.setPagesize(pagesize);
        allVo.setCounts(userLike.size());
        allVo.setPages(userLike.size()/pagesize + 1);
        allVo.setItems(list.toArray());
        return allVo;
    }

    public AllVo comments(Integer page, Integer pagesize, Integer type) {
        //获取当前用户id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
        //从comment表获取数据
        List<Comment> comments = commentsServiceApi.getComments(uid, type);
        //获取发布人信息
        List<UserInfoLikeVo> list = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = userInfoServiceApi.getUserInfoById(comment.getPublishUserId());
            UserInfoLikeVo userInfoLikeVo = getUserInfoLikeVo(userInfo);
            userInfoLikeVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(comment.getCreated()));
            list.add(userInfoLikeVo);
        }
        AllVo allVo = new AllVo();
        allVo.setPage(page);
        allVo.setPagesize(pagesize);
        allVo.setCounts(comments.size());
        allVo.setPages(comments.size()/pagesize + 1);
        allVo.setItems(list.toArray());
        return allVo;
    }

    private UserInfoLikeVo getUserInfoLikeVo(UserInfo userInfo) {
        UserInfoLikeVo userInfoLikeVo = new UserInfoLikeVo();
        userInfoLikeVo.setId(Convert.toStr(userInfo.getId()));
        userInfoLikeVo.setAvatar(userInfo.getAvatar());
        userInfoLikeVo.setNickname(userInfo.getNickname());
        return userInfoLikeVo;
    }
}
